import Vue, { DirectiveOptions } from 'vue'
import Router from 'vue-router'

import 'normalize.css'
import ElementUI from 'element-ui'
import SvgIcon from 'vue-svgicon'

import '../styles/element-variables.scss'
import '../styles/index.scss'
import '../assets/icons_antd/iconfont.css' // antd icon

import NProgress from 'nprogress'
import App from './App.vue'
import { addRouterEach } from './kit/auth'
import router, { constantRoutes, addRouteConfigs } from './kit/router'
import { addSubsystemConfigs } from './kit/subsystem'
import store from './store'
import { appModule } from './store/modules/app'
import { globalDataModule } from './store/modules/global-data'
import i18n from './language'
import '../icons/components'
import '../pwa/register-service-worker'
import * as directives from '../directives'
import * as filters from '../filters'
import { asyncRoutes, subsystems } from '../router'

Vue.use(Router)
addRouteConfigs(...constantRoutes)
addRouteConfigs(...asyncRoutes)
addSubsystemConfigs(...subsystems)

Vue.use(ElementUI, {
  size: appModule.componentSize, // Set element-ui default size
  i18n: (key: string, value: string) => i18n.t(key, value)
})

Vue.use(SvgIcon, {
  tagName: 'svg-icon',
  defaultWidth: '1em',
  defaultHeight: '1em'
})

// Register global directives
Object.keys(directives).forEach(key => {
  Vue.directive(key, (directives as { [key: string ]: DirectiveOptions })[key])
})

// Register global filter functions
Object.keys(filters).forEach(key => {
  Vue.filter(key, (filters as { [key: string ]: Function })[key])
})

Vue.config.productionTip = false
const needErrorLog = true
if (needErrorLog) {
  Vue.config.errorHandler = function(error, vm, info) {
    appModule.addErrorLog({
      vm,
      error,
      info,
      url: window.location.href
    })
  }
}

globalDataModule.initGlobalData().then(() => {
  NProgress.configure({ showSpinner: false })
  addRouterEach(router, NProgress)
  new Vue({
    store,
    router,
    i18n,
    render: (h) => h(App)
  }).$mount('#app')
})
